package com.mysiteforme.admin.controller.course;

import com.mysiteforme.admin.entity.course.ChLorePoint;
import com.mysiteforme.admin.entity.course.ChSection;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.util.IdWorker;
import com.mysiteforme.admin.util.QiNiuGetToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysiteforme.admin.service.course.ChLorePointService;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import com.mysiteforme.admin.annotation.SysLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yj
 * @since 2019-04-15
 */
@Controller
@RequestMapping("/chLorePoint")
public class ChLorePointController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChLorePointController.class);

    @Autowired
    private ChLorePointService chLorePointService;

    @Resource
    private QiNiuGetToken qiNiuGetToken;

    @GetMapping("list")
    @SysLog("跳转列表")
    public String list() {
        return "/ytzlcourse/chLorePoint/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChLorePoint> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                       ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<ChLorePoint> layerData = new LayerData<>();
        EntityWrapper<ChLorePoint> wrapper = new EntityWrapper<>();
        if (!map.isEmpty()) {
        }
        if (map.get("lorePointName") != null && map.get("lorePointName") != "") {
            wrapper.like("lore_point_name", (String) map.get("lorePointName"));
        }
        if (map.get("sectionId") != null && map.get("sectionId") != "") {
            wrapper.eq("section_id", (String) map.get("sectionId"));
        }
        Page<ChLorePoint> pageData = chLorePointService.selectPage(new Page<>(page, limit), wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @PostMapping("/getLorePoint")
    @ResponseBody
    @SysLog("请求知识点列表")
    public List<ChLorePoint> listData(ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        EntityWrapper<ChLorePoint> wrapper = new EntityWrapper<>();
        if (map.get("sectionId")!=null&&map.get("sectionId")!=""){
            wrapper.eq("section_id",(String)map.get("sectionId"));
        }

        return chLorePointService.selectList(wrapper);
    }

    @GetMapping("add")
    @SysLog("跳转新增页面")
    public String add() {
        return "/ytzlcourse/chLorePoint/add";
    }

    @PostMapping("add")
    @SysLog("保存新增数据")
    @ResponseBody
    public RestResponse add(ChLorePoint chLorePoint) {
        if (null == chLorePoint.getSectionId() || "" == chLorePoint.getSectionId()) {
            return RestResponse.failure("所属课程不能为空");
        }
        chLorePoint.setId(IdWorker.getId());
        chLorePoint.setCreationBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        chLorePoint.setCreationDate(new Date());
        boolean insert = chLorePointService.insertLorePoint(chLorePoint);
        if (insert) {
            return RestResponse.success();
        } else
            return RestResponse.failure("系统繁忙");
    }

    @GetMapping("edit")
    @SysLog("跳转编辑页面")
    public String edit() {
        return "/ytzlcourse/chLorePoint/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑数据")
    public RestResponse edit(ChLorePoint chLorePoint) {
        if (null == chLorePoint.getId() || "" == chLorePoint.getId()) {
            return RestResponse.failure("ID不能为空");
        }
        chLorePoint.setModifyedDate(new Date());
        chLorePoint.setModifyedBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());

        boolean update = chLorePointService.updateLorePointById(chLorePoint);
        if (update) {
            return RestResponse.success();
        } else
            return RestResponse.failure("系统繁忙");

    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除数据")
    public RestResponse delete(@RequestParam(value = "id", required = false) String id) {
        if (null == id || "" == id) {
            return RestResponse.failure("ID不能为空");
        }
        String videoUrl = chLorePointService.getVideoUrl(id);
        qiNiuGetToken.deleteQiniuP(videoUrl);
        boolean del = chLorePointService.deleteLorePointById(id);
        if (del) {
            return RestResponse.success();
        } else
            return RestResponse.failure("系统繁忙");

    }

    @PostMapping("getUploadToken")
    @ResponseBody
    @SysLog("七牛云token获取")
    public RestResponse upload(@RequestParam(value = "suffix", required = true) String suffix) {
        if (null == suffix || "" == suffix) {
            return RestResponse.failure("文件格式错误");
        }
        String randomName = "video/"+IdWorker.getId() + suffix;
        String token = qiNiuGetToken.getUpToken(randomName);
        Map<String, Object> map = new HashMap<>();
        if (token == null || "" == token) {
            return RestResponse.failure("token获取失败");
        }
        map.put("token", token);
        map.put("filename", randomName);
        System.out.println(map.size());
        return RestResponse.success().setData(map);
    }


    @PostMapping("/getVideoUrl")
    @ResponseBody
    @SysLog("获取视频地址")
    public RestResponse getVideoUrl(@RequestParam("id") String id) {
        String url = chLorePointService.getVideoUrl(id);
        if (url != null && url != "") return RestResponse.success().setData(url);
        else return RestResponse.failure("系统繁忙");
    }

    @PostMapping("/deleteVideo")
    @ResponseBody
    @SysLog("删除视频地址")
    public RestResponse getVideoUrl(@RequestParam("key") String key, @RequestParam("id") String id) {
        if (key != "" && key != null) {
            qiNiuGetToken.deleteQiniuP(key);
            return RestResponse.success();
        } else {
            return RestResponse.failure("系统繁忙");
        }
    }

//    @RequestMapping(value = "/qiniucallbackInfo")
//    public void vedioInfo(HttpServletRequest request, HttpServletResponse response){
//        try {
//            // 接收七牛回调过来的内容
//            String line = "";
//            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
//            StringBuilder sb = new StringBuilder();
//            while ((line = br.readLine()) != null) {
//                sb.append(line);
//            }
//            // 设置返回给七牛的数据
//            System.out.println(sb.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        int i =0;
//        while(i<100){
//            System.out.println("七牛回复！！！！——————————————————————————————————————————————————++++++++++++++");
//            i++;
//        }
//    }
}